package com.tensquare.user.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by WF on 2020/7/27 16:13
 * jwt鉴权拦截器
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.得到请求头
        String header = request.getHeader("Authorization");
        System.out.println("header[拦截器] = " + header);
        //2.判断是否存在
        if(!StringUtils.isEmpty(header) && header.startsWith("Bearer ")){
            //2.1)从第七个位置开始截取
            String token = header.substring(7);
            //2.2)解析token
            Claims claims = jwtUtil.parseToken(token);
            //2.3)判断是否有值
            if(claims != null){
                request.setAttribute("claims",claims);
            }
        }
        return true;
    }
}
